import axios, { AxiosInstance, Method } from 'axios';
import env from '@/utils/helpImportMetaEnv';

// 根据具体情况修改
export interface HttpResponse<T = any> {
  statusCode: number;
  message: string;
  successFlag: boolean;
  result: T;
}

const http: AxiosInstance = axios.create({
  baseURL: env.VITE_API_PREFIX,
  headers: {},
  timeout: 5000,
});

http.interceptors.request.use(
  (config) => {
    return config;
  },
  (err) => {
    return Promise.reject(err);
  }
);

http.interceptors.response.use(
  (res) => {
    if (res.status === 200 || res.status === 201) {
      return res;
    }
  },
  (err) => {
    // switch (err.response.status) {
    //   case 401:

    //     break;

    //   default:
    //     break;
    // }
    return Promise.reject(err);
  }
);

/**
 * @description 泛型 T 代表接口返回数据的类型； 泛型 D 代表参数的类型
 * @param url 请求路径
 * @param method 请求方式
 * @param data 请求参数
 * @returns 接口返回值
 */
export default async function request<T, D = any>(url: string, method: Method | string, data?: D): Promise<HttpResponse<T>> {
  return new Promise(async (resolve, reject) => {
    try {
      const response = await http.request({
        url,
        method,
        [method.toLowerCase() === 'get' ? 'params' : 'data']: data,
      });
      resolve(response.data);
    } catch (error) {
      reject(error);
    }
  });
}
